package com.feng.leetcode;

import java.util.concurrent.CountDownLatch;

public class L41 {
    public static void main(String[] args) {
        int[] nums = {1};
        int i = firstMissingPositive(nums);
        System.out.println(i);
    }

    public static int firstMissingPositive(int[] nums) {
        int index = nums.length;
        for (int i = nums.length - 1; i >= 0; i--) {
            int t = nums[i];

            while (!(t > nums.length || t <= 0 || t == nums[t -1])) {

                int temp = nums[t-1];
                nums[t - 1] = t;
                t = temp;
            }
            if (i+1 != nums[i]) {
                index = i;
            }
        }

        if (index != nums.length && index + 1 == nums[index]) {
            for (int i = 0; i < nums.length; i++) {
                if (i+ 1 != nums[i]) {
                    index = i;
                }
            }
        }
        return index + 1;
    }
}
